package com.jacen.etl.dao;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import com.jacen.etl.entity.EtlEntity;
import com.jacen.etl.util.HttpParamCaster;
import com.jacen.etl.util.SqlCondition;

public class EtlDao extends BaseDao<EtlEntity>{

	/**
	 * 分页查询所有实体
	 */
	
	@SuppressWarnings("unchecked")
	public List<EtlEntity> getPage(Session session, int page, int size, Map<String, Object> mapParams) {
		String sql = "from EtlEntity t where 1=1 %s order by t.createDate desc";
		SqlCondition cond = getPageCondition(mapParams);
		sql = String.format(sql, cond.getCondition());
		Query query = session.createQuery(sql);
		setQueryCondition(query, cond.getParams());
		query.setFirstResult((page - 1) * size).setMaxResults(size);
		return (List<EtlEntity>) query.list();
	}
	/**
	 * 根据条件查询实体总数
	 */
	public long getCount(Session session, Map<String, Object> mapParams){
		String sql = "select count(*) from EtlEntity t where 1=1 %s";
		SqlCondition cond = getPageCondition(mapParams);
		sql = String.format(sql, cond.getCondition());
		Query query = session.createQuery(sql);
		setQueryCondition(query, cond.getParams());
		return ((Long) query.uniqueResult()).longValue();
	}
	
	
	private SqlCondition getPageCondition(Map<String, Object> mapParams) {
		SqlCondition cond = new SqlCondition();
		if(HttpParamCaster.paramIsNotEmpty(mapParams.get("entitySchema"))) cond.and().like("upper(t.entitySchema)", mapParams.get("entitySchema").toString().toUpperCase());
		if(HttpParamCaster.paramIsNotEmpty(mapParams.get("entityName"))) cond.and().like("upper(t.entityName)", mapParams.get("entityName").toString().toUpperCase());
		if(HttpParamCaster.paramIsNotEmpty(mapParams.get("runCycle"))) cond.and().equal("t.runCycle", mapParams.get("runCycle"));
		if(HttpParamCaster.paramIsNotEmpty(mapParams.get("runEnable"))) cond.and().equal("t.runEnable", Integer.valueOf(mapParams.get("runEnable").toString()));
		return cond;
	}
	
	private void setQueryCondition(Query query, List<Object> list) {
		for (int i = 0; i < list.size(); i++) {
			Object obj = list.get(i);
			query.setParameter(i, obj);
		}
	}
	
}


